<template>
  <el-upload
    class="upload-demo"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :before-upload="beforeUpload"
    :on-exceed="handleExceed"
    v-bind="$attrs"
    :file-list="fileList"
    :http-request="upload"
  >
    <template v-if="!$attrs.drag">
      <el-button size="small" type="primary">{{ $attrs.clickText }}</el-button>
      <div slot="tip" class="el-upload__tip">
        {{ $attrs.hint }}
      </div>
    </template>
    <template v-else>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">{{ $attrs.clickText }}<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">
        {{ $attrs.hint }}
      </div>
    </template>
  </el-upload>
</template>

<script>
import { upload } from "@/api/common";
export default {
  props: {
    defaultValue: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      fileList: [],
    };
  },
  watch: {
    fileList: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$emit("change", val);
        this.$emit("input", val);
      },
    },
    defaultValue: {
      deep: true,
      immediate: true,
      handler(val) {
        this.fileList = val;
      },
    },
  },
  mounted() {
    // eslint-disable-next-line vue/no-mutating-props
    // this.item.options.defaultValue = this.fileList;
  },
  methods: {
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      const link = document.createElement("a");
      link.href = file.url;
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10; // 2MB limit

      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过10MB',
          type: 'warning',
        });
        return false;
      }
      const allowedTypes = ["image/gif", "image/jpg", "image/jpeg", "image/png", "application/pdf"];
      if (!allowedTypes.includes(file.type)) {
        this.$message({
          message: '不支持的文件类型，请上传 GIF、JPG、JPEG、PNG 或 PDF 文件',
          type: 'warning',
        });
        return false;
      }
      return allowedTypes && isLt2M;
    },
    beforeRemove(file, fileList) {
      // 在这里执行额外的操作，例如弹出确认框
      return new Promise((resolve, reject) => {
        // this.$confirm(`确定移除 ${file.name}？`)
        //   .then(() => {
        //     // 用户点击了确定，文件将被移除
        //     resolve(true);
        //     // 执行其他操作...
        //     // eslint-disable-next-line vue/no-mutating-props
        //     this.defaultValue = fileList;
        //   })
        //   .catch(() => {
        //     // 用户点击了取消，文件将保留
        //     resolve(false);
        //   });
        const newFileList = Object.assign([],this.fileList)
        newFileList.forEach((item,index) => {
          if(item.uid === file.uid) {
            newFileList.splice(index, 1)
          }
        })
        this.fileList = newFileList;
      });
    },
    upload(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      upload(formData).then((res) => {
        if (res.code == 200) {
          this.$message.success("成功");
          this.fileList = [
            ...this.fileList,
            {
              name: res.data.originalFileName,
              size: res.data.size,
              type: res.data.fileType,
              uid: res.data.id,
              status: "done",
              url: `${process.env.VUE_APP_BASE_API}/file/getFile/${res.data.bucketName}/${res.data.name}`,
              fileName: res.data.originalFileName,
            },
          ];
        } else {
          this.$message.error("失败");
        }
      });
    },
  },
};
</script>

<style>
</style>